package org.zephyr.fastboot.config.shiro;

import jakarta.servlet.Filter;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.event.EventBus;
import org.apache.shiro.event.support.DefaultEventBus;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.spring.LifecycleBeanPostProcessor;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.spring.web.config.DefaultShiroFilterChainDefinition;
import org.apache.shiro.spring.web.config.ShiroFilterChainDefinition;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.zephyr.fastboot.config.security.JwtRealm;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

//@Configuration
public class ShiroConfig {

    /**
     * 配置 LifecycleBeanPostProcessor，用于 Shiro 生命周期管理
     *
     * @return LifecycleBeanPostProcessor 实例
     */
    @Bean
    public static LifecycleBeanPostProcessor lifecycleBeanPostProcessor() {
        return new LifecycleBeanPostProcessor();
    }

    /**
     * 配置 DefaultAdvisorAutoProxyCreator，用于 Spring AOP 的自动代理
     *
     * @return DefaultAdvisorAutoProxyCreator 实例
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
        creator.setProxyTargetClass(true);
        return creator;
    }

    /**
     * 定义自定义的 Realm，用于认证和授权
     *
     * @return JwtRealm 实例
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public JwtRealm jwtRealm() {
        JwtRealm jwtRealm = new JwtRealm();
        jwtRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return jwtRealm;
    }

    /**
     * 配置密码匹配器，用于密码加密和校验
     *
     * @return HashedCredentialsMatcher 实例
     */
    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher();
        matcher.setHashAlgorithmName("SHA-256");
        matcher.setHashIterations(1024);
        return matcher;
    }

    /**
     * 定义 DefaultWebSecurityManager，用于管理 Shiro 的安全操作
     *
     * @param jwtRealm 自定义的 Realm
     * @return DefaultWebSecurityManager 实例
     */
    @Bean("securityManager")
    public DefaultWebSecurityManager securityManager(@Qualifier("jwtRealm") JwtRealm jwtRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        // 设置自定义Realm
        securityManager.setRealm(jwtRealm);

        // 关闭shiroDao功能，关闭session
//        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
//        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
//        // 不需要将ShiroSession中的东西存到任何地方包括Http Session中
//        defaultSessionStorageEvaluator.setSessionStorageEnabled(false);
//        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
//        securityManager.setSubjectDAO(subjectDAO);
//
//        // 配置事件总线
//        securityManager.setEventBus(eventBus());

        return securityManager;
    }

    /**
     * 配置 Shiro 的事件总线
     *
     * @return EventBus 实例
     */
    @Bean
    public EventBus eventBus() {
        return new DefaultEventBus();
    }

    /**
     *  定义 ShiroFilterFactoryBean，用于创建 Shiro 过滤器
     *
     *  @param securityManager SecurityManager 实例
     *  @return ShiroFilterFactoryBean 实例
     *  先经过过滤器，如果检测到请求头存在 token，则用 token 去 login，接着走 Realm 去验证
     */
    @Bean("shiroFilterFactoryBean")
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        // 设置 SecurityManager
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        shiroFilterFactoryBean.setLoginUrl("/login");// 设置登录页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");// 设置未授权页面

        // 设置自定义过滤器
        Map<String, Filter> filters = new HashMap<>();
//        filters.put("jwt", new JwtFilter());
        shiroFilterFactoryBean.setFilters(filters);

        // 设置过滤器链定义
        shiroFilterFactoryBean.setFilterChainDefinitionMap(shiroFilterChainDefinition().getFilterChainMap());

        return shiroFilterFactoryBean;
    }

    /**
     * DefaultShiroFilterChainDefinition 配置
     *
     * @return ShiroFilterChainDefinition 实例
     */
    @Bean
    protected ShiroFilterChainDefinition shiroFilterChainDefinition() {
        DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
        chainDefinition.addPathDefinition("/user/login", "anon"); // 允许匿名访问登录页面
        chainDefinition.addPathDefinition("/user/register", "anon"); // 允许匿名访问注册页面
        chainDefinition.addPathDefinition("/admin/**", "roles[admin]"); // 管理员接口需要管理员角色
//        chainDefinition.addPathDefinition("/**", "jwt"); // 其他接口需要JWT认证
        return chainDefinition;
    }

    /**
     * 配置 AuthorizationAttributeSourceAdvisor，用于 Shiro 注解的支持
     *
     * @param securityManager SecurityManager 实例
     * @return AuthorizationAttributeSourceAdvisor 实例
     */
    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
        advisor.setSecurityManager(securityManager);
        return advisor;
    }
}
